<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Grid\BatchRestore;
use App\Admin\Actions\Grid\Restore;
use App\Admin\Repositories\Setting;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Http\Request;

class SettingController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Setting(), function (Grid $grid) {

            $grid->showColumnSelector();
            $grid->enableDialogCreate();
            $grid->setDialogFormDimensions('800px', '500px');

            $grid->quickCreate(function (Grid\Tools\QuickCreate $create) {

                $create->text('title');
                $create->text('variate');
                $create->select('type')
                    ->options(get_setting_types())
                    ->default('text');
                $create->select('group')
                    ->options(get_setting_groups())
                    ->default('site');
                $create->text('remark');

            });

            $grid->column('id')->sortable()->hide();
            $grid->column('title')->editable();
            $grid->column('variate')->editable();
            $grid->column('type')->select(get_setting_types());
            $grid->column('group')->select(get_setting_groups());
            $grid->column('remark')->editable();
            $grid->column('value')->hide();
            $grid->column('created_at')->sortable()->hide();
            $grid->column('updated_at')->sortable()->hide();


            $grid->quickSearch('title');

            $grid->tools()->prepend('<a class="btn btn-primary grid-refresh btn-mini btn-outline" href="setting/config"><i class="fa fa-fw fa-gear"></i>  站点设置</a>');

            // 回收站
            $grid->filter(function (Grid\Filter $filter) {

                // 范围过滤器，调用模型的`onlyTrashed`方法，查询出被软删除的数据。
                $filter->scope('trashed', '回收站')->onlyTrashed();

                $filter->like('title');
                $filter->like('variate');
                $filter->like('value');

            });
            // 行恢复
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                if (request('_scope_') == 'trashed') {
                    $actions->append(new Restore(\App\Models\Setting::class));
                }
            });
            // 批量恢复
            $grid->batchActions(function (Grid\Tools\BatchActions $batch) {
                if (request('_scope_') == 'trashed') {
                    $batch->add(new BatchRestore(\App\Models\Setting::class));
                }
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Setting(), function (Form $form) {

            $id = $form->getKey();

            $form->hidden('id');
            $form->text('title')
                ->required()
                ->rules('required|unique:settings,title,' . $id)
                ->saving(function ($value) {
                    return strip_tags($value);
                });

            $form->text('variate')
                ->required()
                ->rules('required|regex:/^[A-Za-z0-9\-\_]+$/|unique:settings,variate,' . $id);

            $form->select('type')
                ->options(get_setting_types())
                ->default('text')
                ->required()
                ->rules('required');

            $form->select('group')
                ->options(get_setting_groups())
                ->default('site')
                ->required()
                ->rules('required')
                ->saving(function ($group) {
                    clear_settings($group);
                    return $group;
                });

            $form->text('value');
            $form->text('remark');

        });
    }

    public function config(Content $content)
    {

        $content->title('站点设置')
            ->description('站点系统参数配置')
            ->body($this->body());

        return $content;
    }

    protected function body()
    {

        return Form::make(new Setting(), function (Form $form) {
            $form->title('设置');
            $form->action(route('dcat.admin.setting.configSave'));

            $form->disableEditingCheck();
            $form->disableCreatingCheck();
            $form->disableViewCheck();

            $groups = get_setting_groups();

            foreach ($groups as $group => $name) {

                $form->tab($name, function (Form $form) use ($group) {

                    $settings = get_settings($group);

                    foreach ($settings as $setting) {
                        $value = $setting->type == 'switch'
                            ? (bool)$setting->value : $setting->value;
                        if ($setting->remark) {
                            if ($setting->type == 'select') {
                                $form->{$setting->type}('id.' . $setting->id, $setting->title)
                                    ->help($setting->remark)
                                    ->options($setting->option)
                                    ->default($value);
                            } else {
                                $form->{$setting->type}('id.' . $setting->id, $setting->title)
                                    ->help($setting->remark)
                                    ->default($value);
                            }
                        } else {
                            if ($setting->type == 'select') {
                                $form->{$setting->type}('id.' . $setting->id, $setting->title)
                                    ->options($setting->options)
                                    ->default($value);

                            } else {
                                $form->{$setting->type}('id.' . $setting->id, $setting->title)
                                    ->default($value);
                            }
                        }
                    }
                });
            }

        });
    }

    public function configSave(Request $request)
    {
        $ids = $request->input('id');
        foreach ($ids as $id => $value) {
            if (!$id) {
                continue;
            }
            $setting = \App\Models\Setting::with([])->find($id);
            if (!$setting) {
                continue;
            }
            $setting->value = $setting->type == 'switch'
                ? (bool)(int)$value : $value;

            $setting->save();

            if (in_array($setting->group, ['develop', 'env'])) {
                // 设置开发环境
                set_env($setting->variate, $setting->value);
            }
        }
        clear_settings();
        foreach (get_setting_groups() as $group => $name) {
            clear_settings($group);
        }
        return Admin::json()->success('保存成功')->refresh();
    }
}


